<template>
  <div class="app-container home">
    <div class="el-form form">
      <div style="margin-left: auto">
        <el-button class="preview-btn" @click="handlePreview" :disabled="!(formData.templateId)">预览</el-button>
        <el-button
          class="tableAdd"
          type="primary"
          plain
          size="mini"
          @click="onPrimary"
          :disabled="!(formData.templateId)"
          >保存</el-button
        >
        <el-button
          class="tableAdd"
          type="primary"
          plain
          size="mini"
          @click="handleSubmit"
          :disabled="!(formData.templateId)"
          >提交</el-button
        >
      </div>
    </div>
    <el-divider></el-divider>
    <el-row>
      <el-col :span="4">
        <div class="el-form-item el-form-item--mini">
          <el-select
            class="el-input el-input--mini"
            v-model="formData.templateId"
            placeholder="请选择"
            @change="changeStencil"
          >
            <el-option
              v-for="item in roleOptions"
              :key="item.templateId"
              :label="item.templateName"
              :value="item.templateId"
            ></el-option>
          </el-select>
        </div>
        <div class="demo-image__placeholder" v-if="imageUrl">
          <div class="block">
            <el-image :src="imageUrl">
              <div slot="placeholder" class="image-slot">
                加载中<span class="dot">...</span>
              </div>
            </el-image>
            <div class="bigPicture">
              <span>模版缩略图</span>
              <span @click="onBigPicture">
                <img
                  class="operateIcon"
                  src="@/assets/images/bace.png"
                />查看大图</span
              >
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="20">
        <el-form ref="form" size="mini" :model="formData" label-width="100px">
          <el-form-item
            v-for="index in titleNum"
            :key="index * 100"
            :label="index === 1 ? '标题：' : `标题${index - 1}：`"
          >
            <wang-editor
              height="50"
              v-model="textTitle[index === 1 ? 'title' : `title${index - 1}`]"
            ></wang-editor>
          </el-form-item>
          <el-form-item
            v-for="index in imgNum"
            :key="index * 200"
            :label="index === 1 ? '文件：' : `文件${index - 1}：`"
          >
            <image-upload
              :is-show-tip="true"
              list-type="picture-card"
              :limit="1"
              text="上传多媒体文件"
              :fileType="fileType"
              @input="onImg"
              :img-index="index"
              :value="imgContentUrl[index]"
            ></image-upload>
          </el-form-item>
          <el-form-item
            v-for="index in num"
            :key="index"
            :label="index === 1 ? `内容：` : `内容${index - 1}：`"
          >
            <wang-editor
              height="200"
              v-model="
                textContent[index === 1 ? 'content' : `content${index - 1}`]
              "
            ></wang-editor>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-dialog :visible.sync="dialogVisible" title="大图展示">
      <img width="100%" :src="imageUrl" />
    </el-dialog>
    <el-dialog
      :visible.sync="previewShow"
      title="新增页面"
      width="1200px"
      :destroy-on-close="true"
    >
      <div class="preview-content">
        <template-window
          :form-data="formData"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="previewShow = false" class="determine"
          >确定</el-button
        >
        <el-button @click="previewShow = false" class="close">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import ImageUpload from "@/components/ImageUpload/index.vue";
import WangEditor from "@/components/WangEditor/index.vue";
import TemplateWindow from "../template/index.vue";
import {
  addPageManage,
  detailsData,
  editListColumn,
  sumbitPageMg,
} from "@/api/pageManage/page.js";
import { detailsImg } from "@/api/file/index";
import { searcgTmeplatList } from "@/api/templateManage/index";
export default {
  name: "Stencil",
  components: {
    ImageUpload,
    TemplateWindow,
    WangEditor,
  },
  data() {
    return {
      dialogVisible: false, // 大图展示窗口
      previewShow: false, // 预览窗口
      fileType: ["jpg", "gif", "mp4", "doc", "docx", "pdf", "ppt"],
      imageUrl: "",
      num: 0,
      titleNum: 0,
      textTitle: {},
      imgNum: 0,
      imgContentUrl: {},
      roleOptions: [],
      formData: {
        templateId: "",
      },
      textContent: {},
      localImg: [],
      fileDataList: [],
    };
  },
  mounted() {
    const rowData = JSON.parse(this.$route.query.data);
    // 获取模板类型列表
    const params = {
      moduleType: this.$route.query.type === "shelves" ? "2" : "1",
    };
    searcgTmeplatList(params).then((res) => {
      this.roleOptions = res.rows;
      this.roleOptions.forEach((item) => {
        if (item.templateId === rowData.templateId) {
          this.num = item.textNum;
          this.imgNum = item.fileNum;
          this.titleNum = item.titleNum;
          detailsImg({ fileId: item.templateFileId }).then((res) => {
            this.imageUrl = res.data.url;
          });
        }
      });
    });

    if (rowData.pageId) {
      detailsData(rowData.pageId).then((res) => {
        const title = res.data.pagecontent1;
        const content = res.data.pagecontent2;
        const imgData = res.data.pagecontent3;
        this.formData.templateId = res.data.templateId;

        title.forEach((item, index) => {
          this.$set(
            this.textTitle,
            item.orderNum === 1 ? "title" : `title${item.orderNum - 1}`,
            item.titleContent
          );
        });
        content.forEach((item) => {
          this.$set(
            this.textContent,
            item.orderNum === 1 ? "content" : `content${item.orderNum - 1}`,
            item.textContent
          );
        });
        imgData.forEach((item, index) => {
          detailsImg({ fileId: item.fileId }).then((res) => {
            this.$set(this.imgContentUrl, index + 1, [
              {
                url: res.data.url,
                name: res.data.name,
              },
            ]);
            this.fileDataList.push({
              id: item.fileId,
              num: item.orderNum,
              url: res.data.url,
            });
            this.localImg = this.fileDataList.sort((a, b) => {
              return a.num - b.num;
            });
          });
        });
      });
    }
  },
  methods: {
    // 下拉选择模板函数
    changeStencil(val) {
      this.textTitle = {};
      this.imgContentUrl = {};
      this.textContent = {};
      this.localImg = [];
      this.fileDataList = [];
      this.formData = {
        templateId: val,
      };
      let _this = this;
      this.roleOptions.forEach((item) => {
        if (item.templateId === val) {
          this.num = item.textNum;
          this.imgNum = item.fileNum;
          this.titleNum = item.titleNum;
          detailsImg({ fileId: item.templateFileId }).then((res) => {
            this.imageUrl = res.data.url;
          });
          for (let i = 0; i < item.textNum; i++) {
            this.$set(
              this.textContent,
              i === 0 ? "content" : `content${i}`,
              ""
            );
          }
          for (let i = 0; i < item.titleNum; i++) {
            this.$set(this.textTitle, i === 0 ? "title" : `title${i}`, "");
          }
          for (let i = 0; i < item.fileNum; i++) {
            this.$set(this.imgContentUrl, i, []);
          }
        }
      });
    },
    // 图片本地地址回调
    onImg(res, file, index) {
      if (typeof res === "boolean") {
        for (let i = 0; i < this.fileDataList.length; i++) {
          if (this.fileDataList[i].num === index) {
            this.fileDataList.splice(i, 1);
          }
        }
      } else {
        this.fileDataList.push({
          num: index,
          id: res.data.fileId,
          url: file.url,
        });
      }
      this.localImg = this.fileDataList.sort((a, b) => {
        return a.num - b.num;
      });
    },
    //创建方法
    onPrimary() {
      const params = this.handleParams(
        JSON.parse(this.$route.query.data),
        this.textContent,
        this.textTitle,
        this.localImg
      );
      if (params.pageId && Boolean(params.originPageId) === false) {
        editListColumn(params)
          .then((res) => {
            this.$message.success("操作成功！");
            if (this.$route.query.type === "shelves") {
              this.$router.push("/shelves/pageManagemment");
            } else {
              this.$router.push("/enterpriseShowen/pageManagemment");
            }
          })
          .catch((err) => {
            this.$message.error("操作失败！");
          });
      } else {
        addPageManage(params)
          .then((res) => {
            this.$message.success("操作成功！");
            if (this.$route.query.type === "shelves") {
              this.$router.push("/shelves/pageManagemment");
            } else {
              this.$router.push("/enterpriseShowen/pageManagemment");
            }
          })
          .catch((err) => {
            this.$message.error("操作失败！");
          });
      }
    },
    // 提交按钮
    handleSubmit() {
      const params = this.handleParams(
        JSON.parse(this.$route.query.data),
        this.textContent,
        this.textTitle,
        this.localImg
      );
      sumbitPageMg(params).then((res) => {
        this.$message.success("操作成功！");
        if (this.$route.query.type === "shelves") {
          this.$router.push("/shelves/pageManagemment");
        } else {
          this.$router.push("/enterpriseShowen/pageManagemment");
        }
      });
    },
    // 创建参数设置
    handleParams(router, content, title, img) {
      const pagecontent1 = Object.keys(title).map((item, index) => {
        return {
          pageId: router.pageId,
          titleContent: title[item],
          orderNum: index + 1,
        };
      });
      const pagecontent2 = Object.keys(content).map((item, index) => {
        return {
          pageId: router.pageId,
          textContent: content[item],
          orderNum: index + 1,
        };
      });
      const pagecontent3 = img.map((item) => {
        return {
          pageId: router.pageId,
          fileId: item.id,
          orderNum: item.num,
        };
      });
      const params = {
        ...router,
        templateId: this.formData.templateId,
        pagecontent1,
        pagecontent2,
        pagecontent3,
      };
      return params;
    },
    // 大图预览
    onBigPicture() {
      this.dialogVisible = true;
    },
    // 预览按钮
    handlePreview() {
      this.previewShow = true;
      this.formData = {
        ...this.formData,
        ...this.textContent,
        ...this.textTitle,
        previewImg: this.localImg,
      };
    },
  },
};
</script>
<style scoped lang="scss">
.form {
  display: flex;
  justify-content: space-between;

  .el-form-item--mini.el-form-item {
    margin-bottom: 0;
  }

  button {
    width: 80px;
    height: 40px;
  }
}

.preview-btn {
  width: 56px;
  height: 28px;
  border-color: #971111;
  color: #971111;
  padding: 0;
  text-align: center;
  line-height: 28px;

  &:hover {
    border-color: #971111;
    color: #971111;
    background: none;
  }

  &:focus {
    border-color: #971111;
    color: #971111;
    background: none;
  }
}

.bigPicture {
  display: flex;
  justify-content: space-between;

  span {
    font-size: 14px;
    font-family: SourceHanSansCN-Regular, SourceHanSansCN;
    font-weight: 400;
    line-height: 21px;
  }

  span:nth-child(1) {
    color: #333333;
  }

  span:nth-child(2) {
    color: #971111;
    cursor: pointer;

    img {
      height: 16px;
      width: 16px;
    }
  }
}

.preview-content {
  width: 100%;
  height: 700px;
  overflow-y: auto;
}

.app-container {
  ::v-deep .el-dialog__footer {
    text-align: center;

    button {
      width: 60px;
      height: 32px;
      padding: 0;
      text-align: center;
      line-height: 32px;
      border: none;
    }

    .determine {
      background: #971111;
      color: #ffff;

      &:hover {
        background: #971111;
        color: #ffff;
      }
    }

    .close {
      background: #e7e7e7;
      color: #000;

      &:hover {
        background: #e7e7e7;
        color: #000;
      }
    }
  }
}

::v-deep .el-form-item__label {
  font-size: 16px;
}
</style>
